<?php
/*
 * @Author: LDY dong2406@126.com
 * @Date: 2022-09-15 15:18:51
 * @LastEditors: LDY dong2406@126.com
 * @LastEditTime: 2022-09-21 13:02:47
 */

namespace Ldy\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Helper\Table;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
use Webman\Route;
use Ldy\Models\SysApi;

class LdyAdminApi extends Command{

    protected static $defaultName = 'ldy-admin:api';
    protected static $defaultDescription = '添加API接口到管理表';

    /**
     * @return void
     */
    protected function configure()
    {
        $this->addArgument('name', InputArgument::REQUIRED, '输入控制器路径');
    }

    /**
     * @param InputInterface $input
     * @param OutputInterface $output
     * @return int
     */
    protected function execute(InputInterface $input, OutputInterface $output):int
    {
        $name = $input->getArgument('name');
        $routes = Route::getRoutes();
        $class = null;
        $routePrefix = config('plugin.ldy.admin.app.route.prefix');
        $text = ['index'=>'列表','create'=>'表单','store'=>'新增','update'=>'修改','destroy'=>'删除'];

        $parentId = 0;

        foreach($routes as $k=>$obj){
            [$callback, $method] = $obj->getCallback();

            if(empty($callback) || $callback != $name) continue;

            if(!$class) $class = new $callback;
            $title = $class->getTitle();
            $path = str_replace('/'.$routePrefix, '', $obj->getPath());
            [$act] = $obj->getMethods();

            $is = SysApi::where(['path'=>$path, 'action'=>$act])->count();

            if($is) {
                $output->writeln("已存在 [$act][$path]");
                continue;
            }

            if ($method == 'index'){
                $model = SysApi::create(['name'=>$title ? $title:"未命名", 'path'=>$path.'*','action'=>"ALL"]);
                $parentId = $model->id;
            }

            $item = ["name"=>$text[$method], 'path'=>$path,'action'=>$act, 'parent_id'=>$parentId];

            SysApi::create($item);

            $output->writeln("新增接口 [".$text[$method]."][$act][$path]");
        }

        return self::SUCCESS;
    }
}